package com.cysion.study.ui

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.cysion.other.color
import com.cysion.other.startActivity_ex
import com.cysion.study.R
import com.cysion.study.adapter.AddKnowListAdapter
import com.cysion.study.adapter.XitiListAdapter
import com.cysion.study.entity.KnowledgeListEntity
import com.cysion.study.entity.XitiListEntity
import com.cysion.study.helper.UserCache
import com.cysion.study.ktbox.Box
import com.cysion.study.ktbox.base.BaseActivity
import com.cysion.study.ktbox.net.BaseResponseRx
import com.cysion.study.ktbox.net.ErrorHandler
import com.cysion.study.ktbox.utils.whiteTextTheme
import com.cysion.study.net.ApiClient
import com.cysion.study.uibox.bar.TopBar
import com.cysion.study.uibox.dialog.Alert
import com.cysion.study.widget.ShowToast
import com.cysion.study.widget.UIHelper
import com.cysion.targetfun._subscribe
import kotlinx.android.synthetic.main.activity_addknow.*

//课程评价
class AddKnowActivity : BaseActivity(), View.OnClickListener {
    override fun getLayoutId(): Int = R.layout.activity_addknow
    private lateinit var dataAdapter: AddKnowListAdapter
    private lateinit var xitiListAdapter: XitiListAdapter
    private val dataList: MutableList<KnowledgeListEntity> = mutableListOf()
    private val xitiDataList: MutableList<XitiListEntity> = mutableListOf()
    private var curPage = 1


    private var className=""
    private var classTime=""
    private var courseId=""
    override fun initView() {
        courseId = intent.extras.getString("courseId")
        className = intent.extras.getString("className")
        classTime = intent.extras.getString("classTime")
        whiteTextTheme(color(R.color.main_cl))
        topbar.apply {
            setTitle("添加习题与知识点")
//            setTexts("添加", TopBar.Pos.RIGHT)
            setOnTopBarClickListener { obj, pos ->
                if (pos == TopBar.Pos.LEFT) {
                    finish()
                }
            }
        }
        tv_title.text=className
        tv_time.text=classTime
        tv_submit.setOnClickListener {
            submit()
        }
        initClick()

        initList()
    }

    private fun submit() {
        Alert.loading(self)
        ApiClient.api.publishCourse(courseId,UserCache.token)
            .compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    ShowToast("发布成功")
                    finish()
                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)

                }
            }
    }

    private fun initList() {

        //知识点
        zs_list.isNestedScrollingEnabled = false
        dataAdapter = AddKnowListAdapter(dataList, Box.context)
        zs_list.adapter = dataAdapter
        zs_list.layoutManager = LinearLayoutManager(Box.context)
        dataAdapter.setOnTypeClickListener { obj, position, flag ->
            if (flag == AddKnowListAdapter.modify) {//预览
                var bundle= Bundle()
                bundle.putString("courseId", obj.courseId)
                bundle.putSerializable("obj", obj)
                bundle.putString("type","1")
                UIHelper.jump(self, ModifyKnowActivity::class.java,bundle)//编辑知识点
            }else if (flag == AddKnowListAdapter.del) {//删除
                delKnow(obj.id,position)
            }
        }

        //练习题
        xt_list.isNestedScrollingEnabled = false
        xitiListAdapter = XitiListAdapter(xitiDataList, Box.context)
        xt_list.adapter = xitiListAdapter
        xt_list.layoutManager = LinearLayoutManager(Box.context)
        xitiListAdapter.setOnTypeClickListener { obj, position, flag ->
            if (flag == XitiListAdapter.modify) {//编辑习题
                //:1//习题类型 1、单选；2、多选；3、解答题；4、判断题
                var bundle = Bundle()
                bundle.putString("courseId",courseId)
                bundle.putString("type", "1")//1编辑，2新增
                bundle.putSerializable("obj", obj)
                if (obj.type == "1") {
                    bundle.putString("pageType", "1")//pageType  1 单选，2多选
                    UIHelper.jump(self, ModifyChooseTiActivity::class.java,bundle)
                } else if (obj.type == "2") {
                    bundle.putString("pageType", "2")//pageType  1 单选，2多选，3解答，4判断
                    UIHelper.jump(self, ModifyChooseTiActivity::class.java,bundle)
                } else if (obj.type == "3") {
                    bundle.putString("pageType", "3")//pageType  1 单选，2多选，3解答，4判断
                    UIHelper.jump(self, ModifyAnswerTiActivity::class.java,bundle)
                } else if (obj.type == "4") {
                    bundle.putString("pageType", "4")//pageType  1 单选，2多选，3解答，4判断
                    UIHelper.jump(self, ModifyJudgeTiActivity::class.java,bundle)
                }

            }else if (flag == XitiListAdapter.del) {//删除习题
                exerciseDel(obj.id,position)
            }
        }
    }

    private fun initClick() {
        tv_choose_know.setOnClickListener(this)
        tv_modify_know.setOnClickListener(this)
        tv_choose_ti.setOnClickListener(this)
        tv_modify_ti.setOnClickListener(this)

    }
    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_choose_know->{//选择知识点
                var bundle= Bundle()
                bundle.putString("courseId", courseId)
                UIHelper.jumpForResult(self, ChooseKnowListActivity::class.java,bundle,301)//添加习题与知识
            }
            R.id.tv_modify_know->{//编辑知识点
                var bundle= Bundle()
                bundle.putString("courseId", courseId)
                bundle.putString("type","2")//2新加，1编辑
                UIHelper.jump(self, ModifyKnowActivity::class.java,bundle)//编辑知识点
            }
            R.id.tv_choose_ti->{//选择练习题
                var bundle= Bundle()
                bundle.putString("courseId", courseId)
                UIHelper.jumpForResult(self, ChooseTiListActivity::class.java,bundle,401)//选择练习题
            }
            R.id.tv_modify_ti->{//编辑 练习题
                var bundle= Bundle()
                bundle.putString("courseId", courseId)
                UIHelper.jumpForResult(self, ChooseTiTypeActivity::class.java,bundle,401)//选择练习题
            }
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 301 && resultCode == Activity.RESULT_OK) {
            getDataList()//选择知识点返回刷新
        }
    }

    //加载数据
    override fun initData() {
        super.initData()
        getDataList()//获取知识点列表
        getXiTiDataList()//获取习题列表
    }


    private fun getDataList() {
        Alert.loading(self)
        ApiClient.api.knowledgeList(courseId,"","1",curPage.toString(),UserCache.token).compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    stopRefresh()
                    dataList.clear()
                    if (curPage == 1) {
                        if (dataList.size == 0) {
//                            multiView.showEmpty()
                        }
                    }
                    if (it.size <= 0) {
//                        smartLayout.setEnableLoadMore(false)
                    } else {
                        curPage++
                        dataList.addAll(it)
                        dataAdapter.notifyDataSetChanged()
//                        multiView.showContent()
                    }
                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                    stopRefresh()
                }
            }

    }
    private fun getXiTiDataList() {
        Alert.loading(self)
        ApiClient.api.exerciseGetList(courseId,"","1","",curPage.toString(),UserCache.token).compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    stopRefresh()
                    xitiDataList.clear()
                    if (curPage == 1) {
                        if (xitiDataList.size == 0) {
//                            multiView.showEmpty()
                        }
                    }
                    if (it.size <= 0) {
//                        smartLayout.setEnableLoadMore(false)
                    } else {
                        curPage++
                        xitiDataList.addAll(it)
                        xitiListAdapter.notifyDataSetChanged()
//                        multiView.showContent()
                    }
                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                    stopRefresh()
                }
            }

    }

    private fun stopRefresh() {
        /*if (smartLayout.state == RefreshState.Refreshing) {
            smartLayout.finishRefresh()
        } else if (smartLayout.state == RefreshState.Loading) {
            smartLayout.finishLoadMore(100)
        }*/
    }



    //删除知识点至列表
    private fun delKnow(id: String, position: Int) {
        Alert.loading(self)
        ApiClient.api.knowledgeDel(UserCache.token, id)
            .compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    dataList.remove(dataList.get(position))
                    dataAdapter.notifyDataSetChanged()
                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)

                }
            }
    }

    //删除习题至列表
    private fun exerciseDel(id: String, position: Int) {
        Alert.loading(self)
        ApiClient.api.exerciseDel(UserCache.token, id)
            .compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    dataList.remove(dataList.get(position))
                    dataAdapter.notifyDataSetChanged()
                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)

                }
            }
    }
    override fun closeMvp() {
    }

}
